package com.yike.user.strategy.login.type;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yike.common.exception.BusinessException;
import com.yike.common.tool.StringUtil;
import com.yike.user.entity.User;
import com.yike.user.entity.UserAuthorize;
import com.yike.user.mapper.UserAuthorizeMapper;
import com.yike.user.mapper.UserMapper;
import com.yike.user.param.LoginParam;
import com.yike.user.utils.WxAgentAppUtil;
import com.yike.user.utils.WxAppUtil;
import com.yike.user.utils.WxMchAppUtil;
import com.yike.user.vo.wx.WxAppLoginVo;
import lombok.extern.java.Log;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author Sakura
 * @date 2024/8/20 11:26
 * 微信小程序登录
 */
@Component
@Log
public class WxAppLoginStrategy implements LoginTypeStrategy {

    @Autowired
    private WxAppUtil wxAppUtil;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserAuthorizeMapper userAuthorizeMapper;
    @Autowired
    private WxMchAppUtil wxMchAppUtil;
    @Autowired
    private WxAgentAppUtil wxAgentAppUtil;

    @Override
    public User login(LoginParam loginParam) {
        // 微信授权code不能为空
        if (StringUtil.isBlank(loginParam.getAuthCode())) {
            throw new BusinessException(500, "微信授权code不能为空");
        }
        WxAppLoginVo wxAppLoginVo = null;
        // 判断是走客户端过来的还是商户端过来的
        // 获取openID和unionID
        if (loginParam.getLoginSource() == 1) {
            wxAppLoginVo = wxAppUtil.login(loginParam.getAuthCode());
        }
        if (loginParam.getLoginSource() == 2) {
            wxAppLoginVo = wxMchAppUtil.login(loginParam.getAuthCode());
        }
        if (loginParam.getLoginSource() == 3) {
            wxAppLoginVo = wxAgentAppUtil.login(loginParam.getAuthCode());
        }

        if (wxAppLoginVo.getOpenid() == null) {
            throw new BusinessException(500, "微信授权失败");
        }
        // 根据openID或unionId获取用户信息，如果没有则新增用户
        User user = userMapper.selectByOpenIdOrUnionId(
                wxAppLoginVo.getOpenid(),
                wxAppLoginVo.getUnionid());
        if (ObjectUtil.isNull(user)) {
            // 如果用户不存在则创建一个用户
            user = new User();
            user.setUserNo(StringUtil.random(32)); // 生成用户ID
            user.setStatus(1); // 状态为正常
            userMapper.insert(user);
        }

        // 先判断是否已存在信息
        UserAuthorize openIdAuthorize = userAuthorizeMapper.selectOne(Wrappers.lambdaQuery(UserAuthorize.class)
                .eq(UserAuthorize::getSource, loginParam.getLoginSource())
                .eq(UserAuthorize::getUserId, user.getId())
                .eq(UserAuthorize::getType, 2));
        if (ObjectUtil.isNull(openIdAuthorize)) {
            // 不存在则保存
            openIdAuthorize = new UserAuthorize();
            openIdAuthorize.setUserId(user.getId());
            openIdAuthorize.setType(2);
            openIdAuthorize.setSource(loginParam.getLoginSource());
            openIdAuthorize.setContent(wxAppLoginVo.getOpenid());
            openIdAuthorize.setNickname(wxAppLoginVo.getNickname());
            openIdAuthorize.setHeadImgUrl(wxAppLoginVo.getHeadimgurl());
            userAuthorizeMapper.insert(openIdAuthorize);
        } else {
            openIdAuthorize.setNickname(wxAppLoginVo.getNickname());
            openIdAuthorize.setHeadImgUrl(wxAppLoginVo.getHeadimgurl());
            userAuthorizeMapper.updateById(openIdAuthorize);

        }
        if (StringUtil.isNotBlank(wxAppLoginVo.getNickname()) || StringUtil.isNotBlank(wxAppLoginVo.getHeadimgurl())) {
            if (StringUtil.isBlank(user.getNickname())) {
                user.setNickname(wxAppLoginVo.getNickname());
            }
            if (StringUtil.isBlank(user.getHeadImg()) || "https://yk-c-api.prc110.com/api-base/file/NGL6da117PCqnrJIndUlZrzSClXZF30Q".equals(user.getHeadImg())) {
                user.setHeadImg(wxAppLoginVo.getHeadimgurl());
            }
            userMapper.updateById(user);
        }

        // 如果unionID不为空还需要保存unionID信息
        if (StringUtil.isNotBlank(wxAppLoginVo.getUnionid())) {
            // 先判断是否已存在信息
            UserAuthorize unionIdAuthorize = userAuthorizeMapper.selectOne(Wrappers.lambdaQuery(UserAuthorize.class)
                    .eq(UserAuthorize::getSource, loginParam.getLoginSource())
                    .eq(UserAuthorize::getUserId, user.getId())
                    .eq(UserAuthorize::getType, 3));
            if (ObjectUtil.isNull(unionIdAuthorize)) {
                // 不存在则保存
                unionIdAuthorize = new UserAuthorize();
                unionIdAuthorize.setUserId(user.getId());
                unionIdAuthorize.setType(3);
                unionIdAuthorize.setSource(loginParam.getLoginSource());
                unionIdAuthorize.setContent(wxAppLoginVo.getUnionid());
                userAuthorizeMapper.insert(unionIdAuthorize);
            } else {
                unionIdAuthorize.setContent(wxAppLoginVo.getUnionid());
                userAuthorizeMapper.updateById(unionIdAuthorize);
            }
        }

        return user;
    }
}
